const dateClass = function({
  needGetList = false,
  year = new Date().getFullYear(),
  month = new Date().getMonth() + 1,
  day = new Date().getDate()
}) {
  // 是否需要计算当月数据，节省性能，只对 visible 的数据进行计算
  // 数据初始化在最后一行
  this.needGetList = needGetList;
  // 全局变量
  this.dateList = [];
  // 内部方法
  function getFullNumber(num) {
    return ("" + num).length < 2 ? "0" + num : "" + num;
  }
  // 内部方法 计算当前的 date值。 不闭包，让内部能访问外部 this 变量
  var calcDate = () => {
    this.date = this.year + "-" + this.month + "-" + this.day;
  };

  var getDateList = () => {
    calcDate();
    if (this.needGetList) {
      // 月初 星期
      let beginMonthWeek = new Date(this.year, this.month - 1, 1).getDay();
      let beginDate = new Date(this.year, this.month - 1, 1).getDate();
      // 月末 星期
      let endDate = new Date(this.year, this.month, 0).getDate();
      let lastMonthDate = new Date(this.year, this.month - 1, 0).getDate();
      // 缓存列表
      let list = [];
      beginMonthWeek === 0 && (beginMonthWeek = 7);
      // push 第一周前面的数据
      while (beginMonthWeek) {
        list.push({ value: lastMonthDate--, type: "prev" });
        beginMonthWeek--;
      }
      // 翻转
      list.reverse();
      // push 当月数据
      while (endDate) {
        list.push({ value: beginDate++, type: "show" });
        endDate--;
      }
      // push 最后剩余的数据
      let tmp = 1;
      while (list.length < 42) {
        list.push({ value: tmp++, type: "suff" });
      }
      // 赋值
      this.dateList = list;
    }
  };

  // 箭头切换月份对应方法
  this.changeMonth = function(num = 1) {
    let month = +this.month + num;
    if (month === 0) {
      this.year = getFullNumber(+this.year - 1);
      this.month = "12";
    } else if (month === 13) {
      this.year = getFullNumber(+this.year + 1);
      this.month = "01";
    } else {
      this.month = getFullNumber(+month);
    }
    getDateList();
  };

  // 箭头切换年份对应方法
  this.changeYear = function(num = 1) {
    this.year = (+this.year + num).toString();
    getDateList();
  };
  // 设置当前的日期
  this.setDate = function(year, month, day) {
    if (year) {
      let date = new Date(
        year && year >= 1990 ? year : 2020,
        month ? month - 1 : 1,
        day ? day : 1
      );
      this.year = getFullNumber(date.getFullYear());
      this.month = getFullNumber(date.getMonth() + 1);
      this.day = getFullNumber(date.getDate());
      getDateList();
    } else {
      this.year = this.month = this.day = null;
    }
  };

  this.calcDate = calcDate;
  // 设置月
  this.setMonth = function(month) {
    this.month = getFullNumber(month);
    getDateList();
  };
  this.setYear = function(year) {
    this.year = year;
    getDateList();
  };

  this.setDate(year, month, day);
};

export default dateClass;
